package com.yeebo.interceptor;

import com.yeebo.constants.Constants;
import com.yeebo.domain.user.UserTokenDomain;
import com.yeebo.enums.user.UserPlatformEnums;
import com.yeebo.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Api服务拦截器
 */
public class ApiInterceptor extends CommonInterceptor {
    private static Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        super.preHandle(request, response, o);
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            return checkAccessAspect(handlerMethod, request);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {
        super.postHandle(request, response, o, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        super.afterCompletion(request, response, o, e);
    }

    /**
     * 通过注解控制接口请求是否校验通过
     * @param handlerMethod
     * @return true or false
     */
    private boolean checkAccessAspect(HandlerMethod handlerMethod, HttpServletRequest request) {
        Access access = handlerMethod.getMethod().getAnnotation(Access.class);
        if (access != null) {
            if (access.needToken()) {
                String userToken = request.getHeader(Constants.USER_TOKEN_HEADER_KEY);
                UserTokenDomain userTokenDomain = SpringUtils.getBean(UserTokenDomain.class);
                userTokenDomain.checkUserTokenValid(UserPlatformEnums.API.getPlatform(), userToken);
            }
        }
        return true;
    }

}
